package com.yonyou.crm.base.product.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.base.attr.entity.AttrVO;
import com.yonyou.crm.base.product.entity.ProductVO;
import com.yonyou.crm.base.product.entity.SaleUnitVO;
import com.yonyou.crm.base.product.rmitf.IProductRmService;
import com.yonyou.crm.common.enumeration.entity.EnableStateEnum;
import com.yonyou.crm.common.enumeration.entity.WhetherEnum;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;

@RestController
@RequestMapping(value = "/base/products")
public class ProductCtrl {

	@Autowired
	private IProductRmService service;
	
	/**
	 * 查询产品
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);

		@SuppressWarnings("unchecked")
		Page<ProductVO> productPage = service.page(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(productPage);
	}
	
	/**
	 * 产品详情
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}		
		
		return ResponseUtil.getObject(service.detail(id));
	}
	
	/**
	 * 新增产品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		ProductVO vo = getProductVO(request);

		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
				
		return ResponseUtil.getObject(service.insert(vo));
	}
	
	/**
	 * 修改产品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}
		
		ProductVO vo = getProductVO(request);		
		
		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		vo.setId(id);
		
		return ResponseUtil.getObject(service.update(vo));
	}
	
	private String validator(ProductVO vo) {
		
		if (vo == null) {
			return "转换实体失败";
		}

		if (StringUtils.isBlank(vo.getCode())) {
        	return  "编码不能为空";
		}
		
		if (StringUtils.isBlank(vo.getName())) {
        	return  "名称不能为空";
		}
		
		if (vo.getPrdtypeId() == null) {
        	return  "产品分类不能为空";
		}
		
		if (vo.getMeasureId() == null) {
        	return  "主单位不能为空";
		}
		
		if (vo.getPrice() == null) {
        	return  "参考售价不能为空";
		}
		
		if (vo.getAttrGroupId() == null) {
        	return  "属性组不能为空";
		}
		
		return "";
	}
	
	/**
	 * 批量删除产品
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] ids = idsStr.split(",");
		
		if (ids.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}

		String message = service.batchDelete(ids);
		
		Page<ProductVO> page = service.page( getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(page, PCCodeConstant.Success, message);
	}
	
	/**
	 * 批量停启用
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "state", method = RequestMethod.PUT)
	public Object batchUpdateEnableState(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] ids = idsStr.split(",");
		
		if (ids.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		Integer enableState = paramObj.getInt("enableState");
		
		if (enableState == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "停启用状态不能为空");
		}
				
		Page<ProductVO> rPage = service.batchUpdateEnableState(ids, enableState, getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(rPage, enableState.intValue() == EnableStateEnum.ENABLE.getValue() ? "启用成功" : "停用成功");
	}
	
	/**
	 * 参照列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "ref", method = RequestMethod.GET)
	public Object getRefList(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		
		if (paramObj != null) {
			//有分页信息返回分页列表
			if (paramObj.containsKey(HttpKeyConstant.Page) && paramObj.containsKey(HttpKeyConstant.PageSize)) {
				return ResponseUtil.getObject(service.getRefPage(getRequestPage(paramObj), null));
			}
		}
		
		List<ProductVO> voList = service.getRefList(null);
		
		Page<ProductVO> page = new Page<ProductVO>();
		page.setData(voList);
		
		return ResponseUtil.getObject(page);
	}
	
	/**
	 * 分配组织
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "{id}/allocation", method = RequestMethod.PUT)
	public Object allocationOrg(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "产品id不能为空");
		}
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String orgIdStr = paramObj.getString("orgIds");
		
		String[] orgIds = orgIdStr.split(",");
		
		if (orgIds.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		service.allocateOrg(id, orgIds);
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 是否被业务对象引用
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}/cited", method = RequestMethod.GET)
	public Object cited(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}

		JSONObject rObj = new JSONObject();

		Integer flag = service.isCitedByBObj(id) ? WhetherEnum.YES.getValue() : WhetherEnum.NO.getValue();
		rObj.put("flag", flag);
		
		return ResponseUtil.getObject(rObj);
	}
	
	private Page<ProductVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {
		
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		
		return new Page<ProductVO>(page, pageSize);
	}
	
	private ProductVO getProductVO(HttpServletRequest request) {
		
		Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
		fieldClassMap.put("saleUnits", SaleUnitVO.class);
		fieldClassMap.put("attrList", AttrVO.class);
		return RequestUtil.getVO(request, ProductVO.class, fieldClassMap);
	}
}
